package com.qinggeng.project.system.service.impl;


import com.qinggeng.common.enums.OrdersStatusEnum;
import com.qinggeng.common.enums.PayStatusEnum;
import com.qinggeng.common.exception.CustomException;
import com.qinggeng.common.utils.DateUtils;
import com.qinggeng.project.system.domain.*;
import com.qinggeng.project.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.util.CollectionUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class PointSaleServiceImpl implements IPointSaleService {
    @Autowired
    private IOrdersService ordersService;
    @Autowired
    private OrdersDistService ordersDistService;
    @Autowired
    private IOrdersPointService ordersPointService;
    @Autowired
    private IOrdersGoodsService ordersGoodsService;
    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;
    @Autowired
    private TransactionDefinition transactionDefinition;
    @Autowired
    private OrdersArerRecordService ordersArerRecordService;
    @Autowired
    private OrdersPointRecordService ordersPointRecordService;
    @Autowired
    private SumPointSaleService sumPointSaleService;
    @Autowired
    private SinglePointSaleService singlePointSaleService;
    @Autowired
    private IOrdersGiftService ordersGiftService;
    @Autowired
    private IOrdersRecordService ordersRecordService;

    @Override
    public boolean addPointSale(String ordersNo){

        Orders orders=ordersService.selectOrdersByOrdersNo(ordersNo);
        if(null==orders){
            throw new CustomException("订单不存在");
        }
        if(!orders.getStatus().equals(OrdersStatusEnum.进行中.getValue())){
            return false;
        }
        if(!orders.getPayStatus().equals(PayStatusEnum.已支付.getValue())){
            return false;
        }
        List<OrdersGoods> ordersGoodsList=ordersGoodsService.selectOrderGoodListByOrdersId(orders.getOrdersId());
        if(CollectionUtils.isEmpty(ordersGoodsList)){
            log.error("订单商品列表为空");
            throw new CustomException("订单商品列表为空");
        }
        OrdersPoint ordersPoint=ordersPointService.selectOrdersPointByOrdersId(orders.getOrdersId());
        if(null==ordersPoint){
            log.error("订单配送点不存在！");
            throw new CustomException("订单配送点不存在！");
        }

        //统计日期
        String recordDate=getRecordDate(DateUtils.getNowDate(),orders.getDistType());
        TransactionStatus transactionStatus=null;
        try{
            transactionStatus=dataSourceTransactionManager.getTransaction(transactionDefinition);

            //增加区域统计
            ordersArerRecordService.insertOrdersAreaRecord(ordersPoint.getSortArea(),recordDate);
            //增加配送点统计
            ordersPointRecordService.insertOrdersPointRecord(ordersPoint,recordDate);
            //增加订单统计
            ordersRecordService.insertOrdersRecord(orders,ordersPoint.getPointId(),recordDate);

            for (OrdersGoods ordersGoods:ordersGoodsList  ) {
                //更新区域商品销量统计
                sumPointSaleService.updateSumPointSale(ordersPoint.getSortArea(),ordersGoods,recordDate);
                //更新配送点商品销量统计
                singlePointSaleService.updateSinglePointSale(ordersPoint,ordersGoods,recordDate);
            }
            List<OrdersGift> ordersGiftList=ordersGiftService.selectOrdersGiftListByOrdersId(orders.getOrdersId());
            if(CollectionUtils.isEmpty(ordersGiftList)){
                dataSourceTransactionManager.commit(transactionStatus);
                return true;
            }
            for (OrdersGift ordersGift :ordersGiftList    ) {
                //更新区域奖品销量统计
                sumPointSaleService.updateSumPointSale(ordersPoint.getSortArea(),ordersGift,recordDate);
                //更新配送点商品销量统计
                singlePointSaleService.updateSinglePointSale(ordersPoint,ordersGift,recordDate);
            }
            dataSourceTransactionManager.commit(transactionStatus);
            return true;
        }catch (Exception e){
            dataSourceTransactionManager.rollback(transactionStatus);
            log.error("商品销量统计失败{}",e.getMessage());
            throw new CustomException("商品销量统计失败");
        }
    }


    @Override
    public boolean testAddPointSale(String ordersNo){

        Orders orders=ordersService.selectOrdersByOrdersNo(ordersNo);
        if(null==orders){
            throw new CustomException("订单不存在");
        }
        if(!orders.getStatus().equals(OrdersStatusEnum.进行中.getValue())){
            return false;
        }
        if(!orders.getPayStatus().equals(PayStatusEnum.已支付.getValue())){
            return false;
        }

        List<OrdersGoods> ordersGoodsList=ordersGoodsService.selectOrderGoodListByOrdersId(orders.getOrdersId());
        if(CollectionUtils.isEmpty(ordersGoodsList)){
            log.error("订单商品列表为空");
            throw new CustomException("订单商品列表为空");
        }
        OrdersPoint ordersPoint=ordersPointService.selectOrdersPointByOrdersId(orders.getOrdersId());
        if(null==ordersPoint){
            log.error("订单配送点不存在！");
            throw new CustomException("订单配送点不存在！");
        }
        if(orders.getShipTime()==null){
            log.error("发货时间为空");
            throw new CustomException("发货时间为空");
        }
        //统计日期
        String recordDate=getRecordDate(orders.getShipTime(),orders.getDistType());
        TransactionStatus transactionStatus=null;
        try{
            transactionStatus=dataSourceTransactionManager.getTransaction(transactionDefinition);

            //增加区域统计
            ordersArerRecordService.insertOrdersAreaRecord(ordersPoint.getSortArea(),recordDate);
            //增加配送点统计
            ordersPointRecordService.insertOrdersPointRecord(ordersPoint,recordDate);

            for (OrdersGoods ordersGoods:ordersGoodsList  ) {
                //更新区域商品销量统计
                sumPointSaleService.updateSumPointSale(ordersPoint.getSortArea(),ordersGoods,recordDate);
                //更新配送点商品销量统计
                singlePointSaleService.updateSinglePointSale(ordersPoint,ordersGoods,recordDate);
            }
            List<OrdersGift> ordersGiftList=ordersGiftService.selectOrdersGiftListByOrdersId(orders.getOrdersId());
            if(CollectionUtils.isEmpty(ordersGiftList)){
                dataSourceTransactionManager.commit(transactionStatus);
                return true;
            }
            for (OrdersGift ordersGift :ordersGiftList    ) {
                //更新区域奖品销量统计
                sumPointSaleService.updateSumPointSale(ordersPoint.getSortArea(),ordersGift,recordDate);
                //更新配送点商品销量统计
                singlePointSaleService.updateSinglePointSale(ordersPoint,ordersGift,recordDate);
            }
            dataSourceTransactionManager.commit(transactionStatus);
            return true;
        }catch (Exception e){
            dataSourceTransactionManager.rollback(transactionStatus);
            log.error("商品销量统计失败{}",e.getMessage());
            throw new CustomException("商品销量统计失败");
        }
    }

    @Override
    public boolean subtractPointSale(String ordersNo,Long goodsId,Integer goodsNum){
        Orders orders=ordersService.selectOrdersByOrdersNo(ordersNo);
        if(null==orders){
            log.error("订单不存在");
            throw new CustomException("订单不存在");
        }
        OrdersPoint ordersPoint=ordersPointService.selectOrdersPointByOrdersId(orders.getOrdersId());
        if(null==ordersPoint){
            log.error("订单配送点不存在");
            throw new CustomException("订单配送点不存在");
        }
        if(null==orders.getShipTime()){
            log.error("订单发货时间为空");
            throw new CustomException("订单发货时间为空");
        }
        String recordDate=getRecordDate(orders.getShipTime(),orders.getDistType());
        SumPointSale sumPointSale=sumPointSaleService.getSumPointSaleByAreaNameAndGoodsIdAndRecordDate(ordersPoint.getSortArea(),goodsId,recordDate);
        TransactionStatus transactionStatus=null;
        try{
            transactionStatus=dataSourceTransactionManager.getTransaction(transactionDefinition);
            if(sumPointSale!=null){
                boolean b1=sumPointSaleService.subtractSumPointSaleNum(sumPointSale.getId(),goodsNum);
                if(!b1){
                    log.error("减少区域销量失败");
                    throw new CustomException("减少区域销量失败");
                }
            }
            SinglePointSale singlePointSale=singlePointSaleService.getSinglePointSaleByPointIdAndGoodsIdAndRecordDate(ordersPoint.getPointId(),goodsId,recordDate);
            if(singlePointSale!=null){
                boolean b2=singlePointSaleService.subtractSinglePointSaleNum(singlePointSale.getId(),goodsNum);
                if(!b2){
                    log.error("减少配送点销量失败");
                    throw new CustomException("减少配送点销量失败");
                }
            }
            dataSourceTransactionManager.commit(transactionStatus);
            return true;
        }catch (Exception e){
            dataSourceTransactionManager.rollback(transactionStatus);
            throw new CustomException(e.getMessage());
        }

    }


   private String getRecordDate(Date shipTime,String distType){
       //划分时间（晚上22：00）
       Date divideTime=ordersDistService.getDivideTime(shipTime,distType);
       //计算统计日期
       Calendar recordCalendar= Calendar.getInstance();
       recordCalendar.setTime(shipTime);
       if(shipTime.after(divideTime)){
           recordCalendar.add(Calendar.DATE,1);
       }
       return DateUtils.parseDateToStr("yyyy-MM-dd",recordCalendar.getTime());
   }

}
